#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的谓词下推测试
直接测试查询优化器的核心功能
"""

from SemanticAnalysis import Quadruple
from query_optimizer import QueryOptimizer


def test_predicate_pushdown():
    """测试谓词下推优化功能"""
    print("=" * 60)
    print("谓词下推优化核心功能测试")
    print("=" * 60)
    
    optimizer = QueryOptimizer()
    
    # 测试用例1: 简单的FROM + WHERE 谓词下推
    print("\n测试用例1: 简单FROM + WHERE谓词下推")
    quadruples1 = [
        Quadruple("FROM", "Students", "-", "T1"),
        Quadruple(">", "age", "20", "T2"),
        Quadruple("WHERE", "age > 20", "T1", "T3"),
        Quadruple("SELECT", "*", "T3", "T4"),
        Quadruple("RESULT", "T4", "-", "-")
    ]
    
    print("原始四元式:")
    for i, quad in enumerate(quadruples1):
        print(f"{i}: {quad}")
    
    optimized_quads1, stats1 = optimizer.optimize(quadruples1, {})
    
    print(f"\n优化统计: {stats1}")
    
    # 测试用例2: JOIN + WHERE 谓词下推
    print("\n" + "="*60)
    print("测试用例2: JOIN + WHERE谓词下推")
    quadruples2 = [
        Quadruple("FROM", "Students", "-", "T1"),
        Quadruple("=", "s.id", "t.id", "T2"),
        Quadruple("JOIN", "INNER:Teachers:s.id = t.id", "T1", "T3"),
        Quadruple(">", "s.age", "25", "T4"),
        Quadruple("WHERE", "s.age > 25", "T3", "T5"),
        Quadruple("SELECT", "s.name", "T5", "T6"),
        Quadruple("RESULT", "T6", "-", "-")
    ]
    
    print("原始四元式:")
    for i, quad in enumerate(quadruples2):
        print(f"{i}: {quad}")
    
    optimized_quads2, stats2 = optimizer.optimize(quadruples2, {})
    
    print(f"\n优化统计: {stats2}")
    
    # 测试用例3: 复合条件谓词下推
    print("\n" + "="*60)
    print("测试用例3: 复合条件谓词下推")
    quadruples3 = [
        Quadruple("FROM", "Students", "-", "T1"),
        Quadruple(">", "age", "18", "T2"),
        Quadruple("=", "major", "CS", "T3"),
        Quadruple("AND", "age > 18", "major = CS", "T4"),
        Quadruple("WHERE", "(age > 18 AND major = CS)", "T1", "T5"),
        Quadruple("SELECT", "*", "T5", "T6"),
        Quadruple("RESULT", "T6", "-", "-")
    ]
    
    print("原始四元式:")
    for i, quad in enumerate(quadruples3):
        print(f"{i}: {quad}")
    
    optimized_quads3, stats3 = optimizer.optimize(quadruples3, {})
    
    print(f"\n优化统计: {stats3}")
    
    # 总结
    print("\n" + "="*60)
    print("测试总结")
    print("="*60)
    
    total_optimizations = (stats1.get('total_optimizations', 0) + 
                          stats2.get('total_optimizations', 0) + 
                          stats3.get('total_optimizations', 0))
    
    predicate_pushdowns = (stats1.get('predicate_pushdown', 0) + 
                          stats2.get('predicate_pushdown', 0) + 
                          stats3.get('predicate_pushdown', 0))
    
    print(f"总优化次数: {total_optimizations}")
    print(f"谓词下推次数: {predicate_pushdowns}")
    
    if predicate_pushdowns > 0:
        print("✅ 谓词下推优化功能正常工作！")
        print("✅ 查询优化器成功实现了以下优化:")
        print("   - 将WHERE条件下推到FROM操作中")
        print("   - 减少表扫描的数据量")
        print("   - 提高查询执行效率")
    else:
        print("⚠️  谓词下推优化未生效，需要检查实现")
    
    return predicate_pushdowns > 0


def demonstrate_optimization_benefits():
    """演示优化效果"""
    print("\n" + "="*60)
    print("谓词下推优化效果演示")
    print("="*60)
    
    print("\n🔍 优化原理:")
    print("1. 原始查询: FROM Table -> WHERE condition -> SELECT columns")
    print("2. 优化后查询: FROM_FILTERED Table(condition) -> SELECT columns")
    print("3. 优化效果: 减少中间结果集大小，提高执行效率")
    
    print("\n📊 性能提升:")
    print("- 表扫描阶段就应用过滤条件")
    print("- 减少内存使用")
    print("- 降低I/O开销")
    print("- 加速后续操作")
    
    print("\n🎯 适用场景:")
    print("- 单表查询的WHERE条件")
    print("- 连接查询中的选择条件")
    print("- 复合条件的分解下推")
    print("- 聚合查询的预过滤")


if __name__ == "__main__":
    success = test_predicate_pushdown()
    demonstrate_optimization_benefits()
    
    if success:
        print(f"\n🎉 谓词下推优化测试成功！")
    else:
        print(f"\n❌ 谓词下推优化测试失败！")
